package com.wondertek.mist.plugins;

import java.io.File;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;

import com.wondertek.mist.utils.ResourcesDowner;
import com.wondertek.mist.utils.StringUtils;

public class PdfViewPlugin extends CordovaPlugin{

	@Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		
		
		if("showPdf".equals(action)){
			JSONObject param=args.getJSONObject(0);
			String url=param.getString("title"); //IOS版这么写的
			openPdf(url);
		}
		return true;
	}
	
	
	public void openPdf(final String pdffileUrl) {
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			File sdcardDir = Environment.getExternalStorageDirectory();
			File saveDir = new File(sdcardDir, "mistpdf");
			if (!saveDir.exists())
				saveDir.mkdirs();
			File file = new File(saveDir,
					ResourcesDowner.getFileName(pdffileUrl));
			if (file.exists()) {
				showPdf(file);
			} else {
				downloadAndShowPdf(pdffileUrl);
			}
		}

	}
	
	public  void showPdf(File pdfFile) {
		Intent intent = new Intent();
		Uri path = Uri.fromFile(pdfFile);
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(path, "application/pdf");
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		try {
			this.cordova.getActivity().startActivity(intent);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	
	public  void downloadAndShowPdf(final String downloadUrl) {
		new AsyncTask<Void, Void, String>() {

			@Override
			protected void onPreExecute() {
			}

			@Override
			protected String doInBackground(Void... params) {
				try {
					File sdcardDir = Environment.getExternalStorageDirectory();
					File saveDir = new File(sdcardDir, "mistpdf");
					if (!saveDir.exists())saveDir.mkdirs();	
					return ResourcesDowner.downloadFile(downloadUrl,saveDir);
				} catch (Exception e) {
				}
				return "";
			}

			@Override
			protected void onPostExecute(final String filePath) {
				if (!StringUtils.isBlank(filePath)) {
					showPdf(new File(filePath));
				} 
			}
		}.execute();
	}
}
